package com.itcast.rediscache.bitmap;

import cn.hutool.json.JSONUtil;
import com.itcast.rediscache.util.SpringBeanUtil;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * 缓存操作提供类
 * create by zhangtian3 on 2019/6/28
 */
public class CacheProvider {
    //由于当前class不在spring boot框架内（不在web项目中）所以无法使用autowired，使用此种方法进行注入
    private static RedisTemplate<String, String> template = SpringBeanUtil.getBean("redisTemplate", RedisTemplate.class);

    public static <T> boolean set(String key, T value, long validTime) {
        return set(key, JSONUtil.toJsonStr(value), validTime);
    }

    public static boolean set(String key, String value, long validTime) {
        boolean result = template.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = template.getStringSerializer();
                connection.set(serializer.serialize(key), serializer.serialize(value));
                if (validTime > 0L) {
                    connection.expire(serializer.serialize(key), validTime);
                }
                return true;
            }
        });
        return result;
    }

    public static <T> T get(String key, Class<T> clazz) {
        return JSONUtil.toBean(get(key), clazz);
    }

    public static String get(String key) {
        String result = template.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = template.getStringSerializer();
                byte[] value = connection.get(serializer.serialize(key));
                return serializer.deserialize(value);
            }
        });
        return result;
    }

    public static boolean del(String key) {
        Long result = template.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = template.getStringSerializer();
                return connection.del(serializer.serialize(key)) ;
            }
        });
        return result > 0 ? true : false;
    }
}
